package com.zhuangfei.timetable.operater;

import com.zhuangfei.timetable.ResourceTable;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.model.ScheduleConfig;
import com.zhuangfei.timetable.model.ScheduleSupport;
import com.zhuangfei.timetable.utils.ColorUtils;
import com.zhuangfei.timetable.utils.ElementUtil;
import com.zhuangfei.timetable.utils.EventUtil;
import com.zhuangfei.timetable.utils.ScreenUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 课表业务操作者，TimetableView中只涉及属性的设置，方法的具体实现在这里.
 * 常用的方法也就四个，如下
 *
 * @see SimpleOperater#changeWeek(int, boolean)
 * @see SimpleOperater#showView()
 * @see SimpleOperater#updateDateView()
 * @see SimpleOperater#updateSlideView()
 * <p>
 * Created by Liu ZhuangFei on 2018/9/1.
 */
public class SimpleOperater extends AbsOperater {

    private final String CUR_WEEK = "cur_week"; // 当前周
    private final String CUR_TERM = "cur_term"; // 当前学期
    private final String MAR_TOP = "mar_top"; // 课程项的上边距
    private final String MAR_LEFT = "mar_left"; // 左边距
    private final String ITEM_HEIGHT = "item_height"; // 课程项的高度
    private final String THISWEEK_CORNER = "thisweek_corner"; // 本周课程的圆角弧度
    private final String NONWEEK_CORNER = "nonweek_corner"; // 非本周课程的圆角弧度
    private final String MAX_SLIDE_ITEM = "max_slide_item"; // 侧边栏的最大项
    private final String SHOW_NOTCURWEEK = "show_notcurweek"; // 是否显示非本周课程

    private static final String TAG = "SimpleOperater";

    /**
     * 课程表控件
     */
    protected TimetableView mView;
    /**
     * 上下文
     */
    protected Context context;
    /**
     * 保存点击的x坐标
     */
    protected float x;
    /**
     * 保存点击的y坐标
     */
    protected float y;

    /**
     * 布局转换器
     */
    protected LayoutScatter inflater;
    /**
     * 侧边栏
     */
    protected DirectionalLayout weekPanel;
    /**
     * 每天的课程
     */
    protected List<Schedule>[] data = new ArrayList[7];
    /**
     * 每天的面板
     */
    protected DirectionalLayout[] panels = new DirectionalLayout[7];
    /**
     * 根布局
     */
    protected DirectionalLayout containerLayout;
    /**
     * 根布局、日期栏容器
     */
    protected DirectionalLayout dateLayout;
    /**
     * 旗标布局
     */
    protected DirectionalLayout flagLayout;

    /**
     * 本地配置
     */
    protected ScheduleConfig scheduleConfig;

    @Override
    public void init(Context context, AttrSet attrSet, TimetableView view) {
        this.context = context;
        mView = view;
        inflater = LayoutScatter.getInstance(context);
        inflater.parse(ResourceTable.Layout_timetable_layout, mView, mView != null);
        containerLayout = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_id_container);
        dateLayout = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_id_datelayout);
        mView.monthWidthVp(40);
        initAttr(attrSet);
        scheduleConfig = new ScheduleConfig(context);
    }

    /**
     * 获取自定义属性
     *
     * @param attrSet xml属性封装
     */
    protected void initAttr(AttrSet attrSet) {
        if (attrSet == null) {
            return;
        }
        int curWeek = 1;
        if (attrSet.getAttr(CUR_WEEK).isPresent()) {
            curWeek = attrSet.getAttr(CUR_WEEK).get().getIntegerValue();
        }
        String curTerm = "";
        if (attrSet.getAttr(CUR_TERM).isPresent()) {
            curTerm = attrSet.getAttr(CUR_TERM).get().getStringValue();
        }
        int defMarTop = ScreenUtils.vp2px(dateLayout.getContext(), 3);
        int defMarLeft = ScreenUtils.vp2px(dateLayout.getContext(), 3);
        int defItemHeight = ScreenUtils.vp2px(dateLayout.getContext(), 55);
        int marTop = defMarTop;
        if (attrSet.getAttr(MAR_TOP).isPresent()) {
            marTop = attrSet.getAttr(MAR_TOP).get().getDimensionValue();
        }
        int marLeft = defMarLeft;
        if (attrSet.getAttr(MAR_LEFT).isPresent()) {
            marLeft = attrSet.getAttr(MAR_LEFT).get().getDimensionValue();
        }
        int itemHeight = defItemHeight;
        if (attrSet.getAttr(ITEM_HEIGHT).isPresent()) {
            itemHeight = attrSet.getAttr(ITEM_HEIGHT).get().getDimensionValue();
        }
        int thisWeekCorner = 5;
        if (attrSet.getAttr(THISWEEK_CORNER).isPresent()) {
            thisWeekCorner = attrSet.getAttr(THISWEEK_CORNER).get().getDimensionValue();
        }
        int nonWeekCorner = 5;
        if (attrSet.getAttr(NONWEEK_CORNER).isPresent()) {
            nonWeekCorner = attrSet.getAttr(NONWEEK_CORNER).get().getDimensionValue();
        }
        int maxSlideItem = 12;
        if (attrSet.getAttr(MAX_SLIDE_ITEM).isPresent()) {
            maxSlideItem = attrSet.getAttr(MAX_SLIDE_ITEM).get().getIntegerValue();
        }
        boolean isShowNotWeek = true;
        if (attrSet.getAttr(SHOW_NOTCURWEEK).isPresent()) {
            isShowNotWeek = attrSet.getAttr(SHOW_NOTCURWEEK).get().getBoolValue();
        }
        mView.curWeek(curWeek)
                .curTerm(curTerm)
                .marTop(marTop)
                .marLeft(marLeft)
                .itemHeight(itemHeight)
                .corner(thisWeekCorner, true)
                .corner(nonWeekCorner, false)
                .maxSlideItem(maxSlideItem)
                .isShowNotCurWeek(isShowNotWeek);
    }

    @Override
    public DirectionalLayout getDateLayout() {
        return dateLayout;
    }

    /**
     * 获取旗标布局,需要在showView方法执行后执行
     *
     * @return 旗标布局
     */
    @Override
    public DirectionalLayout getFlagLayout() {
        return flagLayout;
    }

    /**
     * 构建侧边栏
     *
     * @param slidelayout 侧边栏的容器
     */
    public void newSlideView(DirectionalLayout slidelayout) {
        if (slidelayout == null) {
            return;
        }
        slidelayout.removeAllComponents();

        ISchedule.OnSlideBuildListener listener = mView.onSlideBuildListener();
        listener.onInit(slidelayout, mView.slideAlpha());
        for (int i = 0; i < mView.maxSlideItem(); i++) {
            Component view = listener.getView(i, inflater, mView.itemHeight(), mView.marTop());
            slidelayout.addComponent(view);
        }
    }

    /**
     * 构建课程项
     *
     * @param originData 某一天的数据集合
     * @param data       某一天的数据集合
     * @param subject    当前的课程数据
     * @param pre        上一个课程数据
     * @param position   构建的索引
     * @param curWeek    当前周
     * @return Component 课程项
     */
    private Component newItemView(final List<Schedule> originData, final List<Schedule> data, final Schedule subject, Schedule pre, int position, int curWeek) {
        // 宽高
        int width = DirectionalLayout.LayoutConfig.MATCH_PARENT;
        int height = mView.itemHeight() * subject.getStep() + mView.marTop() * (subject.getStep() - 1);

        // 边距
        int left = mView.marLeft() / 2;
        int right = mView.marLeft() / 2;
        int top = (subject.getStart() - (pre.getStart() + pre.getStep()))
                * (mView.itemHeight() + mView.marTop()) + mView.marTop();

        if (position != 0 && top < 0) {
            return null;
        }

        // 设置Params
        Component view = inflater.parse(ResourceTable.Layout_item_timetable, null, false);

        DirectionalLayout.LayoutConfig lp = new DirectionalLayout.LayoutConfig(width, height);
        if (position == 0) {
            top = (subject.getStart() - 1) * (mView.itemHeight() + mView.marTop()) + mView.marTop();
        }
        lp.setMargins(left, top, right, 0);

        view.setBackground(ElementUtil.getShapeElement6(Color.TRANSPARENT.getValue()));
        view.setTag(subject);
        StackLayout layout = (StackLayout) view.findComponentById(ResourceTable.Id_id_course_item_framelayout);
        layout.setLayoutConfig(lp);

        boolean isThisWeek = ScheduleSupport.isThisWeek(subject, curWeek);
        Text textView = (Text) view.findComponentById(ResourceTable.Id_id_course_item_course);
        Text countTextView = (Text) view.findComponentById(ResourceTable.Id_id_course_item_count);
        textView.setText(mView.onItemBuildListener().getItemText(subject, isThisWeek));

        countTextView.setText("");
        countTextView.setVisibility(Component.HIDE);

        ShapeElement gd = new ShapeElement();
        if (isThisWeek) {
            textView.setTextColor(new Color(mView.itemTextColorWithThisWeek()));
            Map<String, Integer> colorMap = mView.colorPool().getColorMap();
            if (!colorMap.isEmpty() && colorMap.containsKey(subject.getName())) {
                gd.setRgbColor(new RgbColor(ColorUtils.alphaColor(colorMap.get(subject.getName()), mView.itemAlpha())));
            } else {
                gd.setRgbColor(new RgbColor(mView.colorPool().getColorAutoWithAlpha(subject.getColorRandom(), mView.itemAlpha())));
            }
            gd.setCornerRadius(mView.corner(true));

            List<Schedule> clist = ScheduleSupport.findSubjects(subject, originData);
            int count = 0;
            if (clist != null) {
                for (int k = 0; k < clist.size(); k++) {
                    Schedule schedule = clist.get(k);
                    if (schedule != null && ScheduleSupport.isThisWeek(schedule, curWeek)) {
                        count++;
                    }
                }
            }
            if (count > 1) {
                countTextView.setVisibility(Component.VISIBLE);
                countTextView.setText(count + "");
            }
        } else {
            textView.setTextColor(new Color(mView.itemTextColorWithNotThis()));
            Map<String, Integer> colorMap = mView.colorPool().getColorMap();
            if (!colorMap.isEmpty() && mView.colorPool().isIgnoreUserlessColor() && colorMap.containsKey(subject.getName())) {
                gd.setRgbColor(new RgbColor(ColorUtils.alphaColor(colorMap.get(subject.getName()), mView.itemAlpha())));
            } else {
                gd.setRgbColor(new RgbColor(mView.colorPool().getUselessColorWithAlpha(mView.itemAlpha())));
            }
            gd.setCornerRadius(mView.corner(false));
        }

        textView.setBackground(gd);
        mView.onItemBuildListener().onItemUpdate(layout, textView, countTextView, subject, gd);

        textView.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                List<Schedule> result = ScheduleSupport.findSubjects(subject, originData);
                mView.onItemClickListener().onItemClick(component, result);
            }
        });

        textView.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                mView.onItemLongClickListener().onLongClick(view, subject.getDay(), subject.getStart());
            }
        });

        return view;
    }

    /**
     * 将数据data添加到layout的布局上
     *
     * @param layout  容器
     * @param data    某一天的数据集合
     * @param curWeek 当前周
     */
    private void addToLayout(DirectionalLayout layout, final List<Schedule> data, int curWeek) {
        if (layout == null || data == null || data.size() < 1) {
            return;
        }
        layout.removeAllComponents();

        // 遍历
        List<Schedule> filter = ScheduleSupport.fliterSchedule(data, curWeek, mView.isShowNotCurWeek());
        Schedule pre = null;
        if (filter.size() > 0) {
            pre = filter.get(0);
        }
        for (int i = 0; i < filter.size(); i++) {
            final Schedule subject = filter.get(i);
            Component view = newItemView(data, filter, subject, pre, i, curWeek);
            if (view != null) {
                layout.addComponent(view);
                pre = subject;
            }
        }
    }


    /**
     * 点击panel时的事件响应
     *
     * @param view 空白格子
     * @param y    y坐标
     */
    private void onPanelClicked(Component view, float y) {
        if (mView.isShowFlaglayout()) {
            flagLayout.setVisibility(Component.VISIBLE);
        } else {
            flagLayout.setVisibility(Component.HIDE);
        }

        // 周几，0：周一，6：周日
        int day = 0;

        // 先找到点击的是周几的panel
        for (int i = 0; i < panels.length; i++) {
            if (view == panels[i]) {
                day = i;
                break;
            }
        }

        if (day == -1) {
            return;
        }

        // 判断点击的是第几节课，1：第1节
        final int start = (int) Math.ceil((y / (mView.itemHeight() + mView.marTop())));
        if (!checkPosition(day, start)) {
            mView.onSpaceItemClickListener().onSpaceItemClick(day, start);
        }
        final int finalDay = day;
        flagLayout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mView.onFlaglayoutClickListener().onFlaglayoutClick(finalDay, start);
            }
        });
    }

    /**
     * 判断位置是否有课
     *
     * @param day   周几
     * @param start 课程起始坐标
     * @return true：有课，false：无课
     */
    private boolean checkPosition(int day, int start) {
        List<Schedule> list;
        if (mView.isShowNotCurWeek()) {
            list = ScheduleSupport.getAllSubjectsWithDay(mView.dataSource(), day);
        } else {
            list = ScheduleSupport.getHaveSubjectsWithDay(mView.dataSource(), mView.curWeek(), day);
        }
        boolean isHave = false;
        for (Schedule item : list) {
            if (start == item.getStart() || (start >= item.getStart() && start <= (item.getStart() + item.getStep() - 1))) {
                isHave = true;
            }
        }
        return isHave;
    }

    /**
     * 初始化panel并为panel设置事件监听
     */
    private void initPanel() {
        for (int i = 0; i < panels.length; i++) {
            switch (i) {
                case 0:
                    panels[0] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_1);
                    break;
                case 1:
                    panels[1] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_2);
                    break;
                case 2:
                    panels[2] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_3);
                    break;
                case 3:
                    panels[3] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_4);
                    break;
                case 4:
                    panels[4] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_5);
                    break;
                case 5:
                    panels[5] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_6);
                    break;
                default:
                    panels[6] = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_7);
                    break;
            }
            data[i] = new ArrayList<>();

            /**
             * 点击空白格子时才会触发这个事件
             */
            int finalI = i;
            panels[i].setTouchEventListener(new Component.TouchEventListener() {
                @Override
                public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                    switch (touchEvent.getAction()) {
                        case TouchEvent.PRIMARY_POINT_DOWN:
                            y = EventUtil.getYIntComponent(panels[finalI], touchEvent);
                            return false;
                        default:
                            break;
                    }
                    return false;
                }
            });
            panels[i].setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    onPanelClicked(component, y);
                }
            });
        }
    }

    /**
     * 实现ScrollView的替换,只有在初始化时替换一次
     */
    public void replaceScrollView() {
        if (mView.findComponentById(ResourceTable.Id_id_scrollview) == null) {
            Component view = mView.onScrollViewBuildListener().getScrollView(inflater);
            containerLayout.addComponent(view);
            // 初始化
            weekPanel = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_weekPanel_0);
            flagLayout = (DirectionalLayout) mView.findComponentById(ResourceTable.Id_id_flaglayout);
            initPanel();
        }
    }

    /**
     * 设置旗标布局的配置
     */
    public void applyFlagLayoutConf() {
        mView.hideFlaglayout();
        DirectionalLayout.LayoutConfig lp = new DirectionalLayout.LayoutConfig(mView.monthWidth(), DirectionalLayout.LayoutConfig.MATCH_PARENT);
        weekPanel.setLayoutConfig(lp);
        flagLayout.setBackground(ElementUtil.getShapeElement6(mView.flagBgcolor()));
        float perWidth = getPerWidth();
        mView.onSpaceItemClickListener().onInit(flagLayout, mView.monthWidth(),
                Math.round(perWidth), mView.itemHeight(), mView.marTop(),
                Math.round(mView.marLeft() / 2.0f));
    }

    /**
     * 开始装填数据
     */
    public void startTodo() {
        // 清空、拆分数据
        for (int i = 0; i < 7; i++) {
            data[i].clear();
        }
        List<Schedule> source = mView.dataSource();
        for (int i = 0; i < source.size(); i++) {
            Schedule bean = source.get(i);
            if (bean.getDay() != -1) {
                data[bean.getDay() - 1].add(bean);
            }
        }

        // 排序、填充课程
        ScheduleSupport.sortList(data);
        for (int i = 0; i < panels.length; i++) {
            panels[i].removeAllComponents();
            addToLayout(panels[i], data[i], mView.curWeek());
        }
    }

    /**
     * 设置宽度
     */
    public void applyWidthConfig() {
        setWeekendsVisiable(mView.isShowWeekends());
    }

    /**
     * 绘制课程表
     */
    @Override
    public void showView() {
        if (mView == null || mView.dataSource() == null) {
            return;
        }
        checkConfig();
        replaceScrollView();
        applyFlagLayoutConf();
        applyWidthConfig();

        // 更新日期
        updateDateView();
        updateSlideView();
        startTodo();
    }

    /**
     * 本地配置的加载
     */
    private void checkConfig() {
        if (mView == null || mView.onConfigHandleListener() == null) {
            return;
        }
        if (mView.onConfigHandleListener() != scheduleConfig.getOnConfigHandleListener()) {
            scheduleConfig.setOnConfigHandleListener(mView.onConfigHandleListener());
        }
        scheduleConfig.setConfigName(mView.configName());
        scheduleConfig.use(mView);
    }

    /**
     * 切换周次
     *
     * @param week      周次
     * @param isCurWeek 是否强制设置为当前周
     */
    @Override
    public void changeWeek(int week, boolean isCurWeek) {
        for (int i = 0; i < panels.length; i++) {
            addToLayout(panels[i], data[i], week);
        }
        if (isCurWeek) {
            mView.curWeek(week);
        } else {
            mView.onWeekChangedListener().onWeekChanged(week);
        }
    }

    protected float getPerWidth() {
        float perWidth = 0;
        if (mView.isShowWeekends()) {
            perWidth = (ScreenUtils.getWidthInPx(context) - mView.monthWidth()) / 7;
        } else {
            perWidth = (ScreenUtils.getWidthInPx(context) - mView.monthWidth()) / 5;
        }
        return perWidth;
    }

    /**
     * 更新日期栏
     */
    public void updateDateView() {
        dateLayout.removeAllComponents();

        float perWidth = getPerWidth();

        int height = ScreenUtils.vp2px(dateLayout.getContext(), 50);
        // 日期栏
        ISchedule.OnDateBuildListener listener = mView.onDateBuildListener();
        listener.onInit(dateLayout, mView.dateAlpha());
        Component[] views = mView.onDateBuildListener().getDateViews(inflater, mView.monthWidth(), perWidth, height);
        for (Component component : views) {
            if (component != null) {
                dateLayout.addComponent(component);
            }
        }
        mView.onDateBuildListener().onUpdateDate(mView.curWeek(), mView.curWeek());
        mView.onDateBuildListener().onHighLight();
    }

    /**
     * 侧边栏更新
     */
    @Override
    public void updateSlideView() {
        newSlideView(weekPanel);
    }

    /**
     * 设置周末的可见性
     *
     * @param isShow 周末是否可见
     */
    public void setWeekendsVisiable(boolean isShow) {
        if (isShow) {
            if (panels != null && panels.length > 6) {
                panels[5].setVisibility(Component.VISIBLE);
                panels[6].setVisibility(Component.VISIBLE);
            }
        } else {
            if (panels != null && panels.length > 6) {
                panels[5].setVisibility(Component.HIDE);
                panels[6].setVisibility(Component.HIDE);
            }
        }
    }
}
